#!/bin/bash
set -e

function docker_tag_exists() {
    EXISTS=$(curl -s -i https://registry.hub.docker.com/v2/repositories/$1/tags/$2/ | grep last_updated)
    return $?
}

function build() {
    build_dir="${i}"
    name="os-$(echo ${build_dir} | cut -f2 -d-)"

    version="${VERSION}"
    if [ "${name}" == "os-docker" ]; then
        IFS='-' read -ra dirname <<< "$i"
        IFS='_' read -ra ver <<< "${dirname[2]}"
        version=${ver[0]}

        #TODO: eventually this will go away, and we can use ARCH
        LOCALARCH="${ver[1]}"
        if [ "${LOCALARCH}" != "" ]; then
            SUFFIX="_${LOCALARCH}"
        else
            LOCALARCH="amd64"
            SUFFIX=""
        fi
    else
        LOCALARCH="$ARCH"
        if [ "${LOCALARCH}" != "amd64" ]; then
            SUFFIX="_${LOCALARCH}"
        else
            SUFFIX=""
        fi
    fi

    tag="${OS_REPO}/${name}:${version}${SUFFIX}"

    if [[ "$LOCALARCH" != "$ARCH" ]]; then
        echo "${tag} ($LOCALARCH) is not for this arch $ARCH, skipping"
        return
    fi

    if docker_tag_exists "${OS_REPO}/${name}" "${version}${SUFFIX}"; then
        echo "${tag} EXISTS on Docker Hub, skipping"
        return
    fi

    if [ $(docker images -q ${tag}) ]; then
        echo "== ${tag} EXISTS locally, needs pushing"
        if [ "${name}" == "os-docker" ]; then
            docker run --rm -it ${tag} /engine/docker version | grep Version
            docker run --rm -it ${tag} /engine/docker version | grep Arch
        fi
    else
        echo Building ${tag} from ${build_dir}
        if [ -e ${build_dir}/prebuild.sh ]; then
            ${build_dir}/prebuild.sh "${version}" "${LOCALARCH}"
        fi

        if dapper -d --build -f ${build_dir}/Dockerfile -- -t ${OS_REPO}/${name} ${build_dir}; then
            docker tag ${OS_REPO}/${name} ${tag}
            if [ "${name}" == "os-docker" ]; then
                docker run --rm -it ${tag} /engine/docker version | grep Version
                docker run --rm -it ${tag} /engine/docker version | grep Arch
            fi
        elif [ "$?" != "42" ]; then
            exit 1
        else
            echo "Skipping ${tag}"
            return
        fi
    fi
    echo ${tag} >> dist/images
}

export ARCH=${ARCH:-"amd64"}
BASE=images

source $(dirname $0)/version
cd $(dirname $0)/..

mkdir -p dist
echo > dist/images

image_dirname=${IMAGE_BUILD_NAME:-"[1-9]*"}
for i in $BASE/$image_dirname; do
    build ${i}
done
